package com.zhuiyun.project.api.system.menu.controller;

import com.zhuiyun.project.annotation.OptLog;
import com.zhuiyun.project.api.system.menu.entity.SysMenu;
import com.zhuiyun.project.api.system.menu.model.SysMenuModel;
import com.zhuiyun.project.api.system.menu.service.SysMenuService;
import com.zhuiyun.project.common.constant.UserConstants;
import com.zhuiyun.project.common.controller.BaseController;
import com.zhuiyun.project.common.errorCode.EmErrorCode;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.utils.BeanUtils;
import com.zhuiyun.project.utils.StringUtils;
import com.zhuiyun.project.utils.constants.CommonConstants;
import com.zhuiyun.project.utils.validator.ValidatorUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;


/**
 * 菜单权限Controller
 * 
 * @author ruoyi
 * @date 2023-06-16
 */
@RestController
@Api(tags = "菜单管理")
@Slf4j
@RequestMapping("/system/menu")
public class SysMenuController extends BaseController {

    @Autowired
    private SysMenuService sysMenuService;

    /**
     * @param sysMenu
     * @Author Administrator
     * @Description 查询菜单权限列表
     * @Date 2023/10/26 20:05
     * @Return com.zhuiyun.project.common.response.CommonResult
     */
    @PreAuthorize("@ss.hasPermi('system:menu:list')")
    @ApiOperation(value = "查询菜单权限列表的方法")
    @OptLog(modular = "菜单权限", type = CommonConstants.SELECT, describe = "查询菜单权限列表")
    @GetMapping("/list")
    public CommonResult list(SysMenu sysMenu) {
        log.info("查询菜单信息列表");
        return sysMenuService.listselectSysMenu(sysMenu);
    }

    /**
     * @param sysMenuModel
     * @Author Administrator
     * @Description
     * @Date 2023/10/27 10:21
     * @Return com.zhuiyun.project.common.response.CommonResult
     */
    @PreAuthorize("@ss.hasPermi('system:menu:insert')")
    @ApiOperation(value = "添加菜单权限列表的方法")
    @OptLog(modular = "添加菜单权限", type = CommonConstants.ADD, describe = "添加菜单权限列表")
    @PostMapping
    public CommonResult insertMenu(@RequestBody SysMenuModel sysMenuModel) throws Exception {
        log.info("添加菜单");
        //判断sysMenuModel是否为空或null
        if (ValidatorUtil.ValidationObject(sysMenuModel)) {
            SysMenu sysMenu = new SysMenu();
            BeanUtils.copy(sysMenuModel, sysMenu);
            //判断传过来的值 菜单名称是否已存在
            if (!sysMenuService.checkMenuNameUnique(sysMenu)) {
                return CommonResult.error("新增菜单'" + sysMenuModel.getMenuName() + "'失败，菜单名称已存在");
            } else if (UserConstants.YES_FRAME.equals(sysMenuModel.getIsFrame()) && !StringUtils.ishttp(sysMenu.getPath())) {
                return CommonResult.error("新增菜单'" + sysMenuModel.getMenuName() + "'失败，地址必须以http(s)://开头");
            }
            sysMenu.setCreateBy(getLoginName());
            return sysMenuService.insertSysMenu(sysMenu);
        } else {
            return CommonResult.ok(EmErrorCode.SAVE_ERROR);
        }
    }
    /**
    * @Author Administrator
    * @Description 修改菜单管理
    * @Date 2023/10/27 14:11
    * @Return com.zhuiyun.project.common.response.CommonResult
    */
    @PreAuthorize("@ss.hasPermi('system:menu:edit')")
    @ApiOperation(value = "菜单管理的修改方法")
    @OptLog(modular = "菜单管理", type = CommonConstants.UPDATE, describe = "修改菜单")
    @PutMapping
    public CommonResult editSysMenu(@RequestBody SysMenuModel sysMenuModel) throws Exception{
        log.info("修改菜单");
        if(ValidatorUtil.ValidationObject(sysMenuModel)) {
            SysMenu sysMenu = new SysMenu();
            BeanUtils.copy(sysMenuModel, sysMenu);
            if (!sysMenuService.checkMenuNameUnique(sysMenu)){
                return CommonResult.error("修改菜单'" + sysMenu.getMenuName() + "'失败，菜单名称已存在");
            } else if (UserConstants.YES_FRAME.equals(sysMenu.getIsFrame()) && !StringUtils.ishttp(sysMenu.getPath())) {
                return CommonResult.error("修改菜单'" + sysMenu.getMenuName() + "'失败，地址必须以http(s)://开头");
            } else if (sysMenu.getMenuId().equals(sysMenu.getParentId())) {
                return CommonResult.error("修改菜单'" + sysMenu.getMenuName() + "'失败，上级菜单不能选择自己");
            }
            else {
                return sysMenuService.editSysMenu(sysMenu);
            }

        } else {
            return CommonResult.error(EmErrorCode.UPDATE_ERROR);
        }
    }
    /**
    * @Author Administrator
    * @Description 删除菜单
    * @Date 2023/10/27 14:54
    * @Return com.zhuiyun.project.common.response.CommonResult
    */
    @PreAuthorize("@ss.hasPermi('system:menu:remove')")
    @ApiOperation(value = "菜单管理的删除方法")
    @OptLog(modular = "菜单管理", type = CommonConstants.DELETE, describe = "删除菜单")
    @DeleteMapping("/{menuIds}")
    public CommonResult removeSysMenuById(@PathVariable Long[] menuIds){
        log.info("删除菜单");
        return  sysMenuService.removeSysMenuById(menuIds);
    }
    /**
    * @Author Administrator
    * @Description 根据菜单id查询信息
    * @Date 2023/10/30 8:39
    * @Return com.zhuiyun.project.common.response.CommonResult
    */
    @PreAuthorize("@ss.hasPermi('system:menu:get')")
    @ApiOperation(value = "单查")
    @OptLog(modular = "菜单管理单查", type = CommonConstants.SELECT, describe = "查询菜单")
    @GetMapping("/{menuId}")
    public CommonResult getSysMenuById(@PathVariable Long menuId){
        log.info("根据id查询菜单");
        return CommonResult.ok( sysMenuService.getSysMenuById(menuId));
    }
    /**
    * @Author Administrator
    * @Description 加载对应角色菜单树
    * @Date 2023/10/30 20:35
    * @Return com.zhuiyun.project.common.response.CommonResult
    */
    @ApiOperation(value = "根据角色id查询菜单树")
    @OptLog(modular = "角色管理" , type = CommonConstants.SELECT , describe = "根据角色id查询菜单树")
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public CommonResult roleMenuTreeselect(@PathVariable Long roleId){
        //根据用户id查询到所分配的所有权限
        List<SysMenu> sysMenuList = sysMenuService.selectMenuList(getUserId());
        //再通过角色id查询到所分配的所有权限
        HashMap<String, Object> map = new HashMap<>();
        map.put("checkKey",sysMenuService.selectMenuByRoleId(roleId));
        map.put("menus",sysMenuService.buildMenuTreeSelect(sysMenuList));
        return CommonResult.ok(map);
    }
    /**
    * @Author Administrator
    * @Description 获取菜单下拉树列表
    * @Date 2023/10/31 8:47
    * @Return com.zhuiyun.project.common.response.CommonResult
    */
    @ApiOperation(value = "菜单下拉树查询")
    @OptLog(modular = "角色管理", type = CommonConstants.SELECT, describe = "菜单下拉数查询")
    @GetMapping("/treeselect")
    public CommonResult treeselect(SysMenu sysMenu){
        List<SysMenu> sysMenuList = sysMenuService.selectMenuList(sysMenu, getUserId());
        return CommonResult.ok(sysMenuService.buildMenuTreeSelect(sysMenuList));
    }
}